package com.le.medium.class3;

import org.junit.Test;

/**
 * 用螺旋的方式打印矩阵，比如如下的矩阵
 * 0  1  2  3
 * 4  5  6  7
 * 8  9 10 11
 * 打印顺序为：0 1 2 3 7 11 10 9 8 4 5 6
 */
public class Problem03_PrintMatrixSpiralOrder {

    public static void rotate(int[][] matrix) {
        int ar = 0;
        int ac = 0;
        int br = matrix.length - 1;
        int bc = matrix[0].length - 1;
        while (ar <= br && ac <= bc) {
            printEdge(matrix, ar++, ac++, br--, bc--);
        }
    }

    private static void printEdge(int[][] matrix, int ar, int ac, int dr, int dc) {
        if (ar == dr) {
            // 同行
            for (int i = ac; i <= dc; i++) {
                System.out.print(matrix[ar][i] + "  ");
            }
        } else if (ac == dc) {
            // 同列
            for (int i = ar; i <= dr; i++) {
                System.out.print(matrix[i][ac] + "  ");
            }
        } else {
            int r = ar;
            int c = ac;
            // 打印第一行
            while (c != dc) {
                System.out.print(matrix[ar][c] + "  ");
                c++;
            }
            // 打印右边一列
            while (r != dr) {
                System.out.print(matrix[r][dc] + "  ");
                r++;
            }
            // 打印下边一行
            while (c != ac) {
                System.out.print(matrix[dr][c] + "  ");
                c--;
            }
            // 打印左边一列
            while (r != ar) {
                System.out.print(matrix[r][ac] + "  ");
                r--;
            }
        }
    }

    @Test
    public void test() {
        int[][] matrix = {
                { 1, 2, 3, 4 },
                { 5, 6, 7, 8 },
                { 9, 10, 11, 12 },
                { 13, 14, 15, 16 }
        };
        rotate(matrix);
    }
}
